package com.example.widgethost;

import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class WidgetsContainer extends LinearLayout {
    private static final String TAG = "WidgetsContainer";
    private AppWidgetManager appWidgetManager;

    public WidgetsContainer(@NonNull Context context) {
        super(context);
        init(context);
    }

    public WidgetsContainer(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public WidgetsContainer(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        setOrientation(VERTICAL);
        appWidgetManager = AppWidgetManager.getInstance(context);
    }

    public void addWidgetToScreen(AppWidgetHostView appWidgetHostView) {
        if (appWidgetHostView.getParent() == null) {
            LayoutParams layoutParams = getLayoutParams(appWidgetHostView.getAppWidgetInfo());
            addView(appWidgetHostView, layoutParams);
        } else {
            Log.e(TAG, "this widgetview is already added to its widgets container");
        }
    }

    private LayoutParams getLayoutParams(AppWidgetProviderInfo appWidgetProviderInfo) {
        int minWidth = LayoutParams.WRAP_CONTENT;
        int minHeight = LayoutParams.WRAP_CONTENT;
        if (appWidgetProviderInfo != null) {
            minWidth = appWidgetProviderInfo.minWidth;
            minHeight = appWidgetProviderInfo.minHeight;
        }
        LayoutParams layoutParams = new LayoutParams(minWidth, minHeight);
        return layoutParams;
    }

    private AppWidgetProviderInfo getAppWidgetInfo(int appWidgetId) {
        AppWidgetProviderInfo appWidgetProviderInfo = appWidgetManager.getAppWidgetInfo(appWidgetId);
        return appWidgetProviderInfo;
    }
}